//
//  NewsViewController.m
//  TeamProject_1.0
//
//  Created by lanou3g on 15/12/7.
//  Copyright © 2015年 wey. All rights reserved.
//
#import "FirstCell.h"
#import "SecondCell.h"
#import "ThirdCell.h"
#import "NewsViewController.h"
#import "FirstModel.h"
#import "User.h"
@interface NewsViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
///  collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
/// 流水布局
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *Flowlayout;
// 设置轮播图数据
@property (nonatomic, strong) NSMutableArray *sectionArray1;
///  每日精选故事 title
@property (nonatomic, strong) NSString *sectionTitle2;
/// 精彩游记和专题 title
@property (nonatomic, strong) NSString *sectionTitle3;
///  每日精选故事 数组 (4 个)
@property (nonatomic, strong) NSMutableArray *sectionArray2;
///  精彩游记和专题 可变数组
@property (nonatomic, strong) NSMutableArray *sectionArray3;
///  当前时间戳
@property (nonatomic, strong) NSString *currentTime;
///  搜索button数组[0]国外[1]国内
@property (nonatomic, strong) NSMutableArray *searchArrays;

@end

@implementation NewsViewController

- (NSMutableArray *)sectionArray1 {
    if (!_sectionArray1) {
        _sectionArray1 = [NSMutableArray array];
    }
    return _sectionArray1;
}

- (NSMutableArray *)sectionArray2 {
    if (!_sectionArray2) {
        _sectionArray2 = [NSMutableArray arrayWithCapacity:4];
    }
    return _sectionArray2;
}

- (NSMutableArray *)sectionArray3 {
    if (!_sectionArray3) {
        _sectionArray3 = [NSMutableArray arrayWithCapacity:12];
    }
    return _sectionArray3;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    [self loadData];
}

- (void)loadData {
    kWeakSelf(weakSelf);
    // 数据库 判断是否 有缓存 钥匙串
    [[NetWorkHelper shareInstance] GET:@"http://api.breadtrip.com/v2/index" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        dic = dic[@"data"];
        [weakSelf setData:dic];
        [weakSelf setUpCollectionView];
        [weakSelf.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@, %s,%d",error,__func__,__LINE__);
    }];
    
    // 上 刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"f5");
        [weakSelf.collectionView.mj_header endRefreshing];
    }];
    // 下 加载
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"more");
        [weakSelf.collectionView.mj_footer endRefreshing];
//
        NSLog(@"%@",weakSelf.currentTime);
        [weakSelf loadMoreData];
    }];
}
// 加载更多
- (void)loadMoreData {
    kWeakSelf(weakSelf);
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%ld",[self.currentTime integerValue]];
    [[NetWorkHelper shareInstance] GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * responseObject) {
        weakSelf.currentTime = [responseObject[@"data"][@"next_start"] stringValue];
        NSArray *arr = responseObject[@"data"][@"elements"];
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:arr.count];
       [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           FirstModel *model = [FirstModel firstModelWithDic:arr[idx]];
           [arrM addObject:model];
       }];
//        weakSelf TM 类型错了 第一个 给第二个
        
        [weakSelf.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];


}


- (void) setData:(NSDictionary *)dic {
    self.currentTime = dic[@"data"][@"next_start"];
    ///  搜索数组 国内 国外
    self.searchArrays = dic[@"search_data"];
    
    NSArray *elements = dic[@"elements"];
    ///  取轮播图 title urls
    for (NSDictionary *dic in elements.firstObject[@"data"][0]) {
        NSArray *subs = @[dic[@"image_url"],dic[@"html_url"]];
        [self.sectionArray1 addObject:subs];
    }
    
    for (NSDictionary *subDic in elements) {
        NSInteger typeNum = [subDic[@"type"] integerValue];
        
        switch (typeNum) { // 7 广告 删除
            case 11: // 每日精选故事 title
                self.sectionTitle2 = [subDic[@"data"] firstObject][@"title"];

                break;
            case 10: {// 每日精选故事 arrary
                 FirstModel *model = [FirstModel firstModelWithDic:subDic[@"data"][0]];
                if (!model) {
                      NSLog(@"%@",model.index_title);
                }else{
                  NSLog(@"%@",model.index_title);
                }
                [self.sectionArray2 addObject:model];
//                [self.sectionArray2 addObject:@"2"];
            }
                break;
            case 9: // 热门游记 title
                self.sectionTitle3 = [subDic[@"data" ] firstObject][@"title"];
                break;
            case 12: // 热门游记 array 12 4 一样?
                [self.sectionArray3 addObject:@"3"];
                break;
            case 4:
                [self.sectionArray3 addObject:@"3"];
                break;
                
            default:
                break;
        }
    }
    
}

///  设置 collectionView
- (void) setUpCollectionView {
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.Flowlayout.minimumInteritemSpacing = 1.0;
    self.Flowlayout.minimumLineSpacing = 1.0;
    self.Flowlayout.sectionInset = UIEdgeInsetsMake(1.0,1.0,40.0,1.0);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark --- collectionView 设置
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}
/** 设置 item 的 个数*/
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 1;
    switch (section) {
        case 1:
            count = 4;
            break;
        case 2:
            count = self.sectionArray3.count;
            break ;
        default:
            break;
    }
    return count;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray * arr = @[@""];
    
    switch (indexPath.section) {
        case 0:
            arr = @[@"1"];
            break;
        case 1:
            arr = self.sectionArray2.copy;
            break;
        case 2:
            arr = self.sectionArray3.copy;
            break;
        default:
            break;
    }
    NSString *cellID = [self getCellID:arr[indexPath.row]];
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    return cell;
}

// 设置 cellsize
- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    CGSize size = CGSizeMake(width-2.0, 150.0);
    switch (indexPath.section) {
        case 1:
            size = CGSizeMake(width/2-3.0, 100.0);
            break;
        case 2:
            size = CGSizeMake(width-2.0, 120);
            break;
        default:
            break;
    }
    return size;
}

// 设置 cellId
- (NSString *)getCellID :(NSString *)sender {
    NSString *cellID = @"cell1";
    if ([sender isEqualToString:@"2"]) {
        cellID = @"cell2";
    }
    if ([sender isEqualToString:@"3"]) {
        cellID = @"cell3";
    }
    return cellID;
    
}

/** 设置sectionView */
//- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//
//    if (section) {
//        return CGSizeMake(0, 0);
//    }
//
//    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 44);
//    return size;
//}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//
//    UICollectionReusableView *headerView = nil;
//    if (kind == UICollectionElementKindSectionHeader) {
//        headerView = [UIView
//
//    return headerView;
//
//}

#pragma mark --- 事件
- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"%ld,%ld",indexPath.section,indexPath.item);
}
/** cell1 */
- (void) setUpCell1 {
    
}
/** cell2 */

- (void) setUpCell2 {
    
    
}
/** cell3 */
- (void) setUpCell3 {
    
    
}
/** 左按钮点击 */
- (IBAction)leftBarButton:(id)sender {
    [self.sideMenuViewController presentLeftMenuViewController];
}


@end
